package cn.kgc.education.controller;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.education.entity.User;
import cn.kgc.education.response.ResponseResult;
import cn.kgc.education.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/9/6
 * @description 用于处理前端用户相关请求
 */
@RestController
@RequestMapping("user")
public class UserController {


    @Resource
    private UserService userService;

    //  登录方法
    @RequestMapping("login")
    public ResponseResult login(String username, String password, String captcha, HttpServletRequest request) {
        System.out.println("username = " + username + ", password = " + password + ", code = " + captcha);
        /*
           根据用户名和密码以及验证码判定用户是否登录成功
           1.  判定用户的输入的验证码是否正确    true
           2.  根据用户名和密码查询用户信息   数据库
         */
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");

        // 响应数据给前端浏览器
        ResponseResult responseResult = new ResponseResult();

        if (!code.equals(captcha)) {   //  用户输入的验证码错误
            responseResult.setCode(110);
            responseResult.setMsg("验证码错误");
            return responseResult;
        }

        // 根据用户的用户名和密码查询数据库  where  username = ? and  password = ?
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username)
                .eq("password", SecureUtil.md5(password));

        //  用户信息查询    one   status
        User one = userService.getOne(userQueryWrapper);
        // 判定是否查询到用户信息
        if (ObjectUtils.isNull(one)) {
            responseResult.setCode(110);
            responseResult.setMsg("用户名或密码错误");
            return responseResult;
        }

        // 用户登录成功   将用户信息保存在 session会话中  用户后续业务逻辑的编写
        session.setAttribute("user", one);

        responseResult.setCode(0);
        responseResult.setMsg("认证通过");
        responseResult.setData(one.getStatus());

        return responseResult;
    }


    //  获取用户基本信息
    @RequestMapping("getUserInfo")
    public ResponseResult getUserInfo(String username) {

        // 调用业务层  查询用户详细信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User one = userService.getOne(userQueryWrapper);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setData(one);

        return responseResult;
    }


    // 编辑个人信息
    @RequestMapping("personalInfo")
    public ResponseResult editPersonalInfo(String username, String tel, String email) {

        // 根据用户名  修改用户信息   set  tel = ? ,email = ?  where username = ?

        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();   //  更新条件
        userUpdateWrapper.set("tel", tel)
                .set("email", email)
                .eq("username", username);


        boolean update = userService.update(userUpdateWrapper);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setMsg("编辑成功");

        return responseResult;


    }


    // 修改个人密码  editPersonalPassword
    @RequestMapping("editPersonalPassword")
    public ResponseResult editPersonalPassword(String oldPWD, String newPWD, HttpServletRequest request) {

        /*
         *   如何实现密码修改的业务?
         *   1.  判定用户的旧密码是否正确     如何知道当前用户的旧密码  ?
         *   2.  更新用户密码
         * */

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Integer id = user.getId();

        User usr = userService.getById(id);
        String DBPassword = usr.getPassword();  //  根据用户名 从数据库中查询的密码   密文


        ResponseResult responseResult = new ResponseResult();
        //  比较用户输入的旧密码 和数据库中查询的密码是否一致    oldPWD  明文
        if (!SecureUtil.md5(oldPWD).equals(DBPassword)) {
            responseResult.setCode(110);
            responseResult.setMsg("旧密码不正确");
            return responseResult;
        }

        //  根据用户的id  修改用户新密码
        usr.setPassword(SecureUtil.md5(newPWD));
        userService.updateById(usr);

        // 密码修改成功
        responseResult.setCode(0);
        responseResult.setMsg("密码修改成功");

        return responseResult;
    }


    //  用户数据分页处理     /user/page   参数1   页码   参数2  每页显示的条数
    @RequestMapping("page")
    public ResponseResult userPage( Integer  page, Integer limit,String username,String email) {

        // 1.  创建分页对象
        Page<User> userPage = new Page<>(page, limit);
        // 2.  分页查询   搜索的分页 共用一个接口
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq(StringUtils.isNotBlank(username),"username",username)
                        .eq(StringUtils.isNotBlank(email),"email",email);

        userService.page(userPage,userQueryWrapper);

        // 3. 获取分页数据     数据总条数   当前页数据

        long total = userPage.getTotal();   //  数据总条数
        List<User> records = userPage.getRecords();  //  当前页数据


        // 4. 封装 分页数据   返回前端页面进行数据展示
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setCount(total);
        responseResult.setData(records);

        return responseResult;
    }


    // 删除用户信息    "1,2,3,4"
    @RequestMapping("delete")
    public ResponseResult  deleteUser(String ids){

        // 将字符串id  处理成集合
        String[] batchIds = ids.split(",");
        ArrayList<Integer> intIds= new ArrayList<>();
        for (String batchId : batchIds) {
            intIds.add(Integer.valueOf(batchId));
        }



        // 批量删除
        userService.removeBatchByIds(intIds);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(0);
        responseResult.setMsg("删除成功");
        return responseResult;
    }


    @RequestMapping("addOrUpdate")
    public ResponseResult  addOrUpdateUser(User user){
        ResponseResult responseResult = new ResponseResult();

        //  判定 用户是否是添加操作
        Integer id = user.getId();
        String username = user.getUsername();
        if (id==null){  //  添加    判定用户名是否重复
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("username",username);
            User one = userService.getOne(userQueryWrapper);

            if (ObjectUtils.isNotNull(one)){
                responseResult.setCode(110);
                responseResult.setMsg("用户名已存在");
                return  responseResult;
            }

            // 用户名不存在   设置一个默认密码    111111
            user.setPassword(SecureUtil.md5("111111"));
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
        }

        //  编辑或添加操作
        userService.saveOrUpdate(user);

        responseResult.setCode(0);
        responseResult.setMsg("操作成功");

        return  responseResult;
    }

}
